package com.github.cosycode.imgtool.tool;

import com.github.cosycode.common.util.io.IoUtils;
import com.github.cosycode.imgtool.util.PathUtils;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

import java.awt.*;
import java.awt.datatransfer.*;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * <b>Description : </b>
 * <p>
 * <b>created in </b> 2022/1/7
 * </p>
 *
 * @author CPF
 * @since 1.0
 **/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ClipboardTool {

    /**
     * 将 粘贴板中的图片 保存到本地磁盘, 存放到在指定文件夹下, 并将路径写回到 粘贴板.
     *
     * @param preFixPath 存储路径
     */
    public static void saveClipboardImgAndReplaceToPath(String preFixPath) throws IOException, UnsupportedFlavorException {
        Image imageFromClipboard = getImageFromClipboard();
        String fileName = "pic-bed" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd-hhmmssSSS")) + ".png";
        if (PathUtils.isEndWithFileSeparator(preFixPath)) {
            preFixPath += PathUtils.FILE_SPLIT_PATTERN;
        }
        final String filePath = preFixPath + fileName;
        assert imageFromClipboard != null;
        IoUtils.savePic(imageFromClipboard, new File(filePath), "png");

        // 保存至系统剪贴板
        StringSelection stsel = new StringSelection(String.format("![%s](%s)", fileName, filePath));
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stsel, stsel);
    }

    /**
     * 从粘贴板获取 图片对象
     */
    public static Image getImageFromClipboard() throws IOException, UnsupportedFlavorException {
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable cc = clipboard.getContents(null);
        if (cc != null && cc.isDataFlavorSupported(DataFlavor.imageFlavor)) {
            return (Image) cc.getTransferData(DataFlavor.imageFlavor);
        }
        return null;
    }


}
